import { io } from "socket.io-client";
import { reactive } from "vue";

class SocketService {
    constructor() {
        this.socket = null;
        // 使用 Vue 的 reactive 定义响应式状态
        this.state = reactive({
            onlineCount: 0,  // 当前在线人数
            totalCount: 0,  // 累计登录人数
        });
        this.connected = false; // 用于标记是否已连接
    }

    // 初始化 Socket 连接
    connect() {
        if (!this.socket) {
            this.socket = io("http://localhost:3000");

            // 监听连接成功
            this.socket.on("connect", () => {
                this.connected = true;
                console.log("Socket 连接已建立");
            });

            // 监听在线人数
            this.socket.on("updateOnlineCount", (count) => {
                this.state.onlineCount = count;
            });

            // 监听累计登录人数
            this.socket.on("updateTotalCount", (count) => {
                this.state.totalCount = count;
            });

            // 监听连接错误
            this.socket.on("connect_error", (error) => {
                console.error("Socket 连接错误:", error);
            });

            // 监听断开连接
            this.socket.on("disconnect", () => {
                this.connected = false;
                console.log("Socket 已断开");
            });
        }
    }

    // 触发登录事件
    login() {
        if (this.socket) {
            this.socket.emit("userLogin");
            console.log("用户登录事件已发送");
        } else {
            console.warn("Socket 未连接，无法发送登录事件");
        }
    }

    // 断开连接
    disconnect() {
        if (this.socket) {
            // 移除所有监听器
            this.socket.off("updateOnlineCount");
            this.socket.off("updateTotalCount");
            this.socket.off("connect");
            this.socket.off("connect_error");
            this.socket.off("disconnect");

            // 断开连接
            this.socket.disconnect();
            this.socket = null;
            this.connected = false;

            console.log("Socket 已断开并清理事件");
        }
    }
}

// 导出单例模式
export default new SocketService();
